package com.example.demo.service.impl;

import com.example.demo.service.DeductStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author Code Farmer
 * @date 2020/5/8 17:21
 */
@Service
public class DeductStockServiceImpl implements DeductStockService {

    @Autowired
    private ValueOperations<String, String> valueOperations;

    @Override
    public String deductStock() {
        synchronized (this) {
            int stock = Integer.parseInt(
                    Optional.ofNullable(valueOperations.get("stock")).orElse("0")
            );
            if (stock > 0) {
                int realStock = stock - 1;
                valueOperations.set("stock", String.valueOf(realStock));
                System.out.println("扣减成功，剩余库存：" + realStock);
            } else {
                System.out.println("扣减失败，剩余不足");
            }
        }
        return "end";
    }
}
